<template>
  <div class="gantt-demo">
    <h2>甘特图演示</h2>
    <div class="gantt-container">
      <!-- 左侧项目列表表格 -->
      <div class="project-list">
        <h3>项目列表</h3>
        <vxe-table
          ref="projectTable"
          :data="projectList"
          height="500"
          border
          stripe
          highlight-hover-row
          highlight-current-row
          :current-row.sync="currentProjectRow"
          @cell-click="onProjectClick"
        >
          <vxe-column field="id" title="项目ID" width="80"></vxe-column>
          <vxe-column field="name" title="项目名称" width="200"></vxe-column>
          <vxe-column field="manager" title="项目经理" width="120"></vxe-column>
          <vxe-column field="status" title="状态" width="100">
            <template #default="{ row }">
              <span :class="getStatusClass(row.status)">{{ row.status }}</span>
            </template>
          </vxe-column>
          <vxe-column field="progress" title="进度" width="100">
            <template #default="{ row }">
              <div class="progress-bar">
                <div 
                  class="progress-fill" 
                  :style="{ width: row.progress + '%' }"
                ></div>
                <span class="progress-text">{{ row.progress }}%</span>
              </div>
            </template>
          </vxe-column>
        </vxe-table>
      </div>

      <!-- 右侧甘特图 -->
      <div class="gantt-chart">
        <div class="gantt-header">
          <h3>{{ currentProject.name || '请选择项目' }}</h3>
          <div v-if="currentProject.name" class="project-info">
            <span class="info-item">项目经理: {{ currentProject.manager }}</span>
            <span class="info-item" :class="getStatusClass(currentProject.status)">
              状态: {{ currentProject.status }}
            </span>
            <span class="info-item">进度: {{ currentProject.progress }}%</span>
          </div>
        </div>
        <div v-if="routerChange" id="gantt_here" style="width:100%; height:450px;" :class="{ 'loading': isLoading }">
          <div v-if="isLoading" class="loading-overlay">
            <div class="loading-spinner"></div>
            <p>加载甘特图数据中...</p>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { gantt } from 'dhtmlx-gantt'

export default {
  name: 'GanttDemo',
  data() {
    return {
      routerChange:false,
      currentProject: {},
      currentProjectRow: null,
      isLoading: false,
      ganttInitialized: false,
      initializationInProgress: false,
      projectList: [
        {
          id: 1,
          name: '网站重构项目',
          manager: '张三',
          status: '进行中',
          progress: 65
        },
        {
          id: 2,
          name: '移动端APP开发',
          manager: '李四',
          status: '计划中',
          progress: 20
        },
        {
          id: 3,
          name: '数据库优化',
          manager: '王五',
          status: '已完成',
          progress: 100
        },
        {
          id: 4,
          name: '用户体验改进',
          manager: '赵六',
          status: '进行中',
          progress: 45
        }
      ],
      ganttData: {
        1: {
          data: [
            {id: 1, text: "需求分析", start_date: "2024-01-01", duration: 5, progress: 1, parent: 0},
            {id: 2, text: "UI设计", start_date: "2024-01-08", duration: 7, progress: 1, parent: 0},
            {id: 3, text: "前端开发", start_date: "2024-01-16", duration: 10, progress: 0.8, parent: 0},
            {id: 4, text: "后端开发", start_date: "2024-01-16", duration: 12, progress: 0.6, parent: 0},
            {id: 5, text: "测试", start_date: "2024-02-05", duration: 5, progress: 0.3, parent: 0},
            {id: 6, text: "部署上线", start_date: "2024-02-12", duration: 2, progress: 0, parent: 0}
          ],
          links: [
            {id: 1, source: 1, target: 2, type: "0"},
            {id: 2, source: 2, target: 3, type: "0"},
            {id: 3, source: 2, target: 4, type: "0"},
            {id: 4, source: 3, target: 5, type: "0"},
            {id: 5, source: 4, target: 5, type: "0"},
            {id: 6, source: 5, target: 6, type: "0"}
          ]
        },
        2: {
          data: [
            {id: 1, text: "市场调研", start_date: "2024-02-01", duration: 3, progress: 1, parent: 0},
            {id: 2, text: "产品规划", start_date: "2024-02-05", duration: 5, progress: 0.8, parent: 0},
            {id: 3, text: "原型设计", start_date: "2024-02-12", duration: 6, progress: 0.5, parent: 0},
            {id: 4, text: "开发准备", start_date: "2024-02-20", duration: 3, progress: 0, parent: 0},
            {id: 5, text: "功能开发", start_date: "2024-02-25", duration: 15, progress: 0, parent: 0},
            {id: 6, text: "测试发布", start_date: "2024-03-15", duration: 5, progress: 0, parent: 0}
          ],
          links: [
            {id: 1, source: 1, target: 2, type: "0"},
            {id: 2, source: 2, target: 3, type: "0"},
            {id: 3, source: 3, target: 4, type: "0"},
            {id: 4, source: 4, target: 5, type: "0"},
            {id: 5, source: 5, target: 6, type: "0"}
          ]
        },
        3: {
          data: [
            {id: 1, text: "性能分析", start_date: "2023-11-01", duration: 4, progress: 1, parent: 0},
            {id: 2, text: "索引优化", start_date: "2023-11-06", duration: 6, progress: 1, parent: 0},
            {id: 3, text: "查询优化", start_date: "2023-11-13", duration: 8, progress: 1, parent: 0},
            {id: 4, text: "架构调整", start_date: "2023-11-22", duration: 5, progress: 1, parent: 0},
            {id: 5, text: "测试验证", start_date: "2023-11-28", duration: 3, progress: 1, parent: 0},
            {id: 6, text: "上线部署", start_date: "2023-12-01", duration: 2, progress: 1, parent: 0}
          ],
          links: [
            {id: 1, source: 1, target: 2, type: "0"},
            {id: 2, source: 2, target: 3, type: "0"},
            {id: 3, source: 3, target: 4, type: "0"},
            {id: 4, source: 4, target: 5, type: "0"},
            {id: 5, source: 5, target: 6, type: "0"}
          ]
        },
        4: {
          data: [
            {id: 1, text: "用户调研", start_date: "2024-01-15", duration: 5, progress: 1, parent: 0},
            {id: 2, text: "界面重设计", start_date: "2024-01-22", duration: 8, progress: 0.9, parent: 0},
            {id: 3, text: "交互优化", start_date: "2024-02-01", duration: 6, progress: 0.7, parent: 0},
            {id: 4, text: "可用性测试", start_date: "2024-02-08", duration: 4, progress: 0.2, parent: 0},
            {id: 5, text: "反馈收集", start_date: "2024-02-13", duration: 3, progress: 0, parent: 0},
            {id: 6, text: "最终调整", start_date: "2024-02-17", duration: 4, progress: 0, parent: 0}
          ],
          links: [
            {id: 1, source: 1, target: 2, type: "0"},
            {id: 2, source: 2, target: 3, type: "0"},
            {id: 3, source: 3, target: 4, type: "0"},
            {id: 4, source: 4, target: 5, type: "0"},
            {id: 5, source: 5, target: 6, type: "0"}
          ]
        }
      }
    }
  },
  watch: {
    '$route'(to, from) {
      console.log('路由变化:', to, from);

      // 当路由变化到甘特图页面时，确保甘特图正确初始化
      if (to.name === 'GanttDemo') {
        // 重置状态
        this.ganttInitialized = false

        // 给更多时间让DOM完全渲染和之前的实例完全清理
        setTimeout(() => {
          if (!this.ganttInitialized) {
            this.initGantt()
          }
        }, 200)
      }
    }
  },
  mounted() {
    this.routerChange = true
    // 给DOM一些时间完全渲染
     console.log('mounted 给DOM一些时间完全渲染');
    setTimeout(() => {
      this.initGantt()
    }, 100)
  },
  activated() {
    console.log('组件被激活，重新初始化甘特图');
    // 当使用keep-alive时，组件被激活时重新初始化
    setTimeout(() => {
      if (!this.ganttInitialized) {
        this.initGantt()
      }
    }, 100)
  },
  beforeRouteLeave(to, from, next) {
    console.log('beforeRouteLeave');
      this.routerChange = false
      next()
  },
  beforeDestroy() {
    console.log('组件销毁前清理甘特图实例');
    this.destroyGantt()
  },
  deactivated() {
     this.routerChange = false
    console.log('组件被停用，清理甘特图实例');
    // 当使用keep-alive时，组件被停用时清理
    this.destroyGantt()
  },
  methods: {
    initGantt() {
      // 防止重复初始化
      if (this.initializationInProgress) {
        console.log("甘特图正在初始化中，跳过重复调用")
        return
      }

      this.initializationInProgress = true

      try {
        // 检查DOM元素是否存在
        const ganttContainer = document.getElementById("gantt_here")
        if (!ganttContainer) {
          console.error("甘特图容器元素未找到")
          this.initializationInProgress = false
          return
        }

        // 简单清理
        this.simpleCleanup()

        // 重置甘特图配置
        this.resetGanttConfig()

        // 直接在原容器上初始化
        gantt.init("gantt_here")
        this.ganttInitialized = true

        // 显示默认提示
        setTimeout(() => {
          this.showEmptyGantt()
          this.initializationInProgress = false
        }, 100)

      } catch (error) {
        console.error("甘特图初始化失败:", error)
        this.ganttInitialized = false
        this.initializationInProgress = false
        this.forceCleanup()
      }
    },



    // 重置甘特图配置
    resetGanttConfig() {
      try {
        // 配置甘特图
        gantt.config.date_format = "%Y-%m-%d"
        gantt.config.scale_unit = "day"
        gantt.config.date_scale = "%m/%d"
        gantt.config.subscales = [
          {unit: "month", step: 1, date: "%Y年%m月"}
        ]
        gantt.config.columns = [
          {name: "text", label: "任务名称", width: 150, tree: true},
          {name: "start_date", label: "开始时间", width: 80},
          {name: "duration", label: "工期", width: 60}
        ]

        // 设置中文本地化
        gantt.locale = {
          date: {
            month_full: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"],
            month_short: ["1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月"],
            day_full: ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"],
            day_short: ["日", "一", "二", "三", "四", "五", "六"]
          },
          labels: {
            new_task: "新任务",
            icon_save: "保存",
            icon_cancel: "取消",
            icon_details: "详细信息",
            icon_edit: "编辑",
            icon_delete: "删除",
            confirm_closing: "",
            confirm_deleting: "确定删除任务吗？",
            section_description: "描述",
            section_time: "时间段",
            section_type: "类型"
          }
        }
      } catch (error) {
        console.error("重置甘特图配置失败:", error)
      }
    },



    // 简单清理甘特图
    simpleCleanup() {
      try {
        // 清空容器
        const ganttContainer = document.getElementById("gantt_here")
        if (ganttContainer) {
          ganttContainer.innerHTML = ''
        }

        // 重置组件状态
        this.ganttInitialized = false
        this.initializationInProgress = false
        this.isLoading = false
      } catch (error) {
        console.warn("简单清理失败:", error)
      }
    },

    // 彻底清理甘特图
    completeCleanup() {
      try {
        // 先尝试正常销毁
        if (this.ganttInitialized && gantt && gantt.destructor) {
          gantt.destructor()
        }
      } catch (error) {
        console.warn("正常销毁失败，继续强制清理:", error)
      }

      try {
        // 强制重置甘特图全局状态
        if (window.gantt) {
          // 重置内部状态
          if (gantt._init_flag !== undefined) gantt._init_flag = false
          if (gantt._rendered !== undefined) gantt._rendered = false
          if (gantt.datastore) gantt.datastore = null

          // 清理事件监听器
          if (gantt.detachAllEvents) gantt.detachAllEvents()
        }
      } catch (error) {
        console.warn("重置甘特图状态失败:", error)
      }

      // 重置组件状态
      this.ganttInitialized = false
      this.initializationInProgress = false
      this.isLoading = false
    },

    forceCleanup() {
      try {
        // 强制清理DOM
        const ganttContainer = document.getElementById("gantt_here")
        if (ganttContainer) {
          ganttContainer.innerHTML = ''
        }

        // 重置状态
        this.ganttInitialized = false
        this.isLoading = false
        this.initializationInProgress = false
      } catch (error) {
        console.error("强制清理失败:", error)
      }
    },

    // 检查甘特图是否可用
    isGanttReady() {
      return this.ganttInitialized &&
             !this.initializationInProgress &&
             gantt &&
             document.getElementById("gantt_here")
    },

    destroyGantt() {
      try {
        this.simpleCleanup()
      } catch (error) {
        console.error("甘特图销毁失败:", error)
        this.forceCleanup()
      }
    },

    // 安全地清空甘特图数据 - 避免使用clearAll
    safelyClearGantt() {
      try {
        // 不使用clearAll，直接用空数据覆盖
        if (this.ganttInitialized && gantt && gantt.parse) {
          gantt.parse({
            data: [],
            links: []
          })
        }
      } catch (error) {
        console.warn("清空甘特图数据时出现错误，将跳过:", error)
      }
    },


    
    showEmptyGantt() {
      try {
        if (this.ganttInitialized && gantt && gantt.parse) {
          // 直接加载空提示数据，不使用clearAll
          gantt.parse({
            data: [{
              id: 1,
              text: "请从左侧选择项目查看甘特图",
              start_date: "2024-01-01",
              duration: 1,
              progress: 0,
              parent: 0
            }],
            links: []
          })
        }
      } catch (error) {
        console.error("显示空甘特图失败:", error)
      }
    },
    
    onProjectClick(params) {
      const { row } = params
      this.currentProject = row
      this.currentProjectRow = row

      // 防止重复点击
      if (this.isLoading) {
        console.log("正在加载中，请稍候...")
        return
      }

      // 直接加载数据，让 loadGanttData 处理初始化逻辑
      this.loadGanttData(row.id)
    },
    
    loadGanttData(projectId) {
      // 如果正在初始化，等待完成
      if (this.initializationInProgress) {
        setTimeout(() => {
          this.loadGanttData(projectId)
        }, 200)
        return
      }

      // 如果甘特图未初始化，先初始化
      if (!this.ganttInitialized) {
        this.initGantt()
        setTimeout(() => {
          this.loadGanttData(projectId)
        }, 300)
        return
      }

      this.isLoading = true

      // 模拟加载延迟，实际项目中这里会是API调用
      setTimeout(() => {
        try {
          const data = this.ganttData[projectId]
          if (data && this.ganttInitialized && gantt && gantt.parse) {
            // 直接加载新数据，不使用clearAll
            gantt.parse(data)
          }
        } catch (error) {
          console.error("加载甘特图数据失败:", error)
        } finally {
          this.isLoading = false
        }
      }, 500)
    },
    
    getStatusClass(status) {
      const statusMap = {
        '进行中': 'status-active',
        '计划中': 'status-planned',
        '已完成': 'status-completed'
      }
      return statusMap[status] || ''
    }
  }
}
</script>

<style scoped>
.gantt-demo {
  padding: 20px;
}

.gantt-container {
  display: flex;
  gap: 20px;
  margin-top: 20px;
}

.project-list {
  flex: 0 0 600px;
}

.gantt-chart {
  flex: 1;
  min-width: 0;
}

.progress-bar {
  position: relative;
  width: 100%;
  height: 20px;
  background-color: #f0f0f0;
  border-radius: 10px;
  overflow: hidden;
}

.progress-fill {
  height: 100%;
  background: linear-gradient(90deg, #4CAF50, #45a049);
  transition: width 0.3s ease;
}

.progress-text {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  font-size: 12px;
  font-weight: bold;
  color: #333;
}

.status-active {
  color: #2196F3;
  font-weight: bold;
}

.status-planned {
  color: #FF9800;
  font-weight: bold;
}

.status-completed {
  color: #4CAF50;
  font-weight: bold;
}

h2, h3 {
  color: #2c3e50;
  margin-bottom: 15px;
}

/* 甘特图样式调整 */
:deep(.gantt_container) {
  border: 1px solid #ddd;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

:deep(.gantt_grid_scale) {
  background: #f8f9fa;
  border-bottom: 2px solid #e9ecef;
}

:deep(.gantt_task_scale) {
  background: #f8f9fa;
  border-bottom: 2px solid #e9ecef;
}

:deep(.gantt_task_line) {
  border-radius: 3px;
}

:deep(.gantt_task_progress) {
  border-radius: 3px;
}

/* 表格行悬停效果 */
:deep(.vxe-table .vxe-body--row:hover) {
  background-color: #f0f9ff !important;
  cursor: pointer;
}

/* 表格选中行效果 */
:deep(.vxe-table .vxe-body--row.row--current) {
  background-color: #e0f2fe !important;
}

.gantt-demo {
  background: #f8f9fa;
  min-height: calc(100vh - 200px);
  border-radius: 8px;
}

.project-list, .gantt-chart {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.project-list h3, .gantt-chart h3 {
  border-bottom: 2px solid #e9ecef;
  padding-bottom: 10px;
  margin-bottom: 20px;
}

.gantt-header {
  margin-bottom: 20px;
}

.project-info {
  display: flex;
  gap: 20px;
  margin-top: 10px;
  font-size: 14px;
}

.info-item {
  padding: 4px 8px;
  background: #f8f9fa;
  border-radius: 4px;
  border: 1px solid #e9ecef;
}

.loading-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(255, 255, 255, 0.9);
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #f3f3f3;
  border-top: 4px solid #2196F3;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 10px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

#gantt_here {
  position: relative;
}
</style>
